use crate::handler::handler::send_response;
use crate::model::request::{User, UserEdit, UserSearch, ID};
use crate::model::user;
use crate::pkg::errno::code::Errno::{ErrDatabase, ErrUserNotFound, ErrValidationAdd, IsOk};
use crate::utils::utils::{encrypt, get_all_fields};
use actix_web::{web, Responder, Result};
use validator::Validate;

// 创建用户
pub async fn create(mut u: web::Json<User>) -> Result<impl Responder> {
    // 1.校验
    match &u.validate() {
        Ok(_) => {
            // 2.查询用户 是否已注册了
            let name = user::query_name(&u.username).await;
            match name {
                Ok(_) => {
                    send_response(
                        ErrValidationAdd("User name repetition.".to_string()),
                        Some(()),
                    )
                    .await
                }
                Err(_) => {
                    // 3.密码，加密
                    let pwd = encrypt(&u.password);
                    u.password = pwd;

                    // 4.新增
                    let create_u = user::create_user(&u).await;

                    match create_u {
                        Ok(()) => send_response(IsOk, None).await,
                        Err(_) => send_response(ErrDatabase, None).await,
                    }
                }
            }
        }
        Err(e) => {
            let errors = get_all_fields(e);
            send_response(ErrValidationAdd(errors.join(", ")), None).await
        }
    }
}

// 编辑
pub async fn edit(params: web::Json<UserEdit>) -> Result<impl Responder> {
    // 查询 id是否存在
    let resp = user::user_detail(params.id).await;
    match resp {
        Ok(i) => {
            let is_name_ok = || {
                let a1 = params.0.username.clone().unwrap();
                let a2 = i.username;
                if a1 == a2 {
                    return true;
                } else {
                    return false;
                }
            };
            // 判断名字是否重复
            if is_name_ok() {
                send_response(
                    ErrValidationAdd("User name repetition.".to_string()),
                    Some(()),
                )
                .await
            } else {
                let edit_res = user::edit_user(&params).await;
                match edit_res {
                    Ok(_) => send_response(IsOk, Some(())).await,
                    Err(_) => send_response(ErrDatabase, None).await,
                }
            }
        }
        Err(_) => send_response(ErrUserNotFound, None).await,
    }
}

// 获取用户名
pub async fn get_user_name(params: web::Path<ID>) -> Result<impl Responder> {
    let name = user::get_name(params.id).await;
    match name {
        Ok(u) => send_response(IsOk, Some(u)).await,
        Err(_) => send_response(ErrUserNotFound, None).await,
    }
}

// 删除账号
pub async fn delete(params: web::Path<ID>) -> Result<impl Responder> {
    let res = user::delete_user(params.id).await;
    match res {
        Ok(()) => send_response(IsOk, Some(())).await,
        Err(_) => send_response(ErrDatabase, None).await,
    }
}

// 查询 详情
pub async fn detail(params: web::Path<ID>) -> Result<impl Responder> {
    let res = user::user_detail(params.id).await;
    match res {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(_) => send_response(ErrUserNotFound, None).await,
    }
}

// 列表
pub async fn list(params: web::Query<UserSearch>) -> Result<impl Responder> {
    let list = user::get_users_list(&params).await;
    match list {
        Ok(i) => send_response(IsOk, Some(i)).await,
        Err(e) => {
            println!("err {:#?}", e);
            send_response(ErrUserNotFound, None).await
        }
    }
}
